package _3响应体;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@WebServlet("/test4")
public class Test4Servlet  extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //告诉客户端我发来的数据是图片
        resp.setContentType("image/jpg");


        //1.输入流读取图片
        int id=(int)(Math.random()*2)+1;
        String filepath=getServletContext().getRealPath("/images/"+id+".jpg");
        InputStream is=new FileInputStream(filepath);

        OutputStream out=resp.getOutputStream();
        byte []buf=new byte[1024];

        int len=0;
        while((len=is.read(buf))!=-1)
        {
            out.write(buf,0,len);
        }

        //2.输出流输出到resp
    }
}
